/*
 * These files are distributed under the terms of the GNU GPLv2, the GNU General
 * Public version 2. See LICENSE.txt
 */
package fileCommodore.plugin.usermenu;

import java.beans.*;
import java.io.*;
import java.util.*;

import javax.swing.*;
import javax.swing.event.*;

public class EntryListModel implements ListModel
{
	private Vector<ListDataListener> listeners = new Vector<ListDataListener>();
	private Vector<Entry> entries = new Vector<Entry>();

	public void addListDataListener(ListDataListener l) {
		listeners.add(l);
	}

	public Object getElementAt(int index) {
		if( isValid(index) )
		{
			return entries.elementAt(index);
		}
		
		return null;
	}

	private boolean isValid(int index) {
		return index >=0 && index < getSize();
	}

	public int getSize() {
		return entries.size();
	}

	public void removeListDataListener(ListDataListener l) {
		listeners.remove(l);
	}

	public String serialize()
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		XMLEncoder e = new XMLEncoder(baos);
		e.writeObject(entries);
		e.flush();
		return new String(baos.toByteArray());
	}
	
	public static EntryListModel deserialize(String data) 
	{
		EntryListModel result = new EntryListModel();
		try
		{
			ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes());
			XMLDecoder d = new XMLDecoder(bais);
			result.entries = (Vector<Entry>) d.readObject();
		}
		catch (Exception ex) 
		{
			// Possibly a new instance with nothing serialized
		}
		return result;
	}

	public void add(Entry e) {
		entries.add(e);
		notifyListeners();
	}
	
	public void remove(Entry e)
	{
		entries.remove(e);
		notifyListeners();
	}
	
	public void up(Entry e)
	{
		if( null != e )
		{
			int i = entries.indexOf(e) - 1;
			if( isValid( i ) )
			{
				entries.remove(e);
				entries.insertElementAt(e, i);
				notifyListeners();
			}
		}
	}
	
	public void down(Entry e)
	{
		if( null != e )
		{
			int i = entries.indexOf(e) + 1;
			if( isValid( i ) )
			{
				entries.remove(e);
				entries.insertElementAt(e, i);
				notifyListeners();
			}
		}
	}
	
	public void notifyListeners()
	{
		ListDataEvent lde = new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, getSize());
		for(ListDataListener ldl: listeners)
		{
			ldl.contentsChanged(lde);
		}
	}
}
